<?php

namespace App\Models;


class Room extends BaseModel
{
    protected $table = "room";
    public $timestamps = false;

    const PREFIX = 'kwx_rooms_';
    const PREFIX_FD = 'fd_';
    const PREFIX_ST = 'st_';

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 按条件查询单条数据
     */
    public function getOne(array $where, $fields = '*')
    {
        $res = $this->multiSelect($fields)->multiWhere($where)->first();
        if ($res) {
            $res = $res->toArray();
        }
        return $res;
    }

    /**
     * 按条件查询全部数据,根据配置显示条数显示
     */
    public function getList(array $where = [], $fields = '*', $order = '', $pageSize = '')
    {
        if ($pageSize) {
            return $this->multiSelect($fields)->multiWhere($where)->multiOrder($order)->paginate($pageSize);
        } else {
            return $this->multiSelect($fields)->multiWhere($where)->multiOrder($order)->get();
        }
    }

    /**
     * 根据条件删除数据
     */
    public function del(array $where)
    {
        return $this->multiWhere($where)->delete();
    }

    /**
     *插入数据
     */
    public function add($data)
    {
        return $this->insertGetId($data);
    }

    /**
     *更新数据
     */
    public function up($where, $data)
    {
        return $this->multiWhere($where)->update($data);
    }

    /**
     * 获取和
     */
    public function getSum($where, $field)
    {
        return $this->multiWhere($where)->sum($field);
    }

    /**
     * 字段递加
     */
    public function inc($where, $field, $n)
    {
        return $this->multiWhere($where)->increment($field, $n);
    }

    public function join($mid, $pwd)
    {
        $json['status'] = 0;
        $where['pwd'] = $pwd;
        $res = $this->getOne($where);
        $players = $this->getRoomInfo($res['id']);
        if ($players) {
            foreach ($players as $k => $v) {
                if ($v['mid'] == $mid) {
                    $json['status'] = 1;
                    $json['msg'] = '加入成功！';
                    $json['role'] = $k;
                    $json['rid'] = $res['id'];
                    $json['mid'] = $mid;
                    $json['type'] = $v['status'];
                    return $json;
                }
            }
        }
        if (!$res) {
            $json['msg'] = '该房间不存在';
            return $json;
        }
        if ($res['player_num'] > 3) {
            $json['msg'] = '该房间已满';
            return $json;
        }
        $member = new Member();
        $memberInfo = $member->getMember($mid);
//        $memberInfo = $member->getMember(1);
        $role = 'r1';
        if ($res['player_num'] == 1) {
            $data['r1'] = $memberInfo['id'];
            $data['player_num'] = 2;
        }
        if ($res['player_num'] == 2) {
            $data['r2'] = $memberInfo['id'];
            $data['player_num'] = 3;
            $role = 'r2';
        }
        $condition['id'] = $res['id'];
        $this->start();
        try {
            $this->up($condition, $data);
            $this->commit();
            $json['status'] = 1;
            $json['msg'] = '加入成功！';
            $json['role'] = $role;
            $json['rid'] = $res['id'];
            $json['mid'] = $mid;
            $json['type'] = 1;
            return $json;
        } catch (\Exception $e) {
            $this->rollBack();
            $json['msg'] = '加入失败';
            return $json;
        }
    }


    /**
     * 获取房间
     */
    public function getRoom($id)
    {
        $key = self::PREFIX . $id;
        $cache = $this->memcache->get($key);
        if (!$cache) {
            $where['id'] = $id;
            $where['host'] = ['<>', ''];
            $data = $this->getOne($where);
            if ($data) {
                $data = $data->toArray();
                $this->memcache->set($key, $data);
            }
            return $data;
        }
        return $cache;
    }

    /**
     * 删除房间
     */
    public function delRoom($id)
    {
        $key = self::PREFIX . $id;
        $this->memcache->delete($key);
    }

    public function createRoom($mid,$round)
    {
        $json['status'] = 1;
        $json['msg'] = '创建成功！';
        $member = new Member();
//        $memberInfo = $member->getMember(session('mid'));
        $memberInfo = $member->getMember($mid);
//        dd($memberInfo);
//        $memberInfo = $member->getMember(1);
        if ($memberInfo['cardnum'] < 1) {
            
            $json['status'] = 0;
            $json['msg'] = '房卡不足，请充值！';
        }
        $this->start();
        try {
            $numPool = new NumberPool();
            $data['pwd'] = $numPool->generatePwd();
            $data['host'] = $memberInfo['id'];
            $data['player_num'] = 1;
            $data['round'] = $round;
            $data['status'] = 1;

            $where['status'] = 0;
            $res = $this->getOne($where);
            if (!$res) {
                $result = $this->add($data);
            } else {
                $condition['id'] = $res['id'];
                $this->up($condition, $data);
            }
            $where2['id'] = $data['pwd'];
            $numData['is_used'] = 1;
//            dd($numData);
            $ra = $numPool->up($where2, $numData);
//            dd($ra);
            $this->commit();
            $id = $res ? $res['id'] : $result;
//            $json['url'] = action('Home\RoomController@getNum', ['role' => 'host', 'rid' => $id, 'mid' => $memberInfo['id']]);
            $json['role'] = 'host';
            $json['rid'] = $id;
            $json['mid'] = $mid;
        } catch (\Exception $e) {
            $this->rollBack();
            $json['status'] = 0;
            $json['msg'] = '创建失败，请稍后再试';
        }
        return $json;
    }


    public function storeRidByFd($fd, $rid)
    {
        $key = self::PREFIX_FD . $fd;
        $this->memcache->set($key, $rid);
    }

    public function getRidByFd($fd)
    {
        $key = self::PREFIX_FD . $fd;
        $rid = $this->memcache->get($key);
        return $rid;
    }

    public function storeRoomInfo($fd, $rid, $mid, $role, $status = 0, $piao = '', $next = '')
    {
        $key = self::PREFIX . $rid;
        $info = $this->memcache->get($key);
        $info[$role]['fd'] = $fd;
        $info[$role]['rid'] = $rid;
        $info[$role]['mid'] = $mid;
        $info[$role]['piao'] = $piao;
        if ($piao || ($piao == 0)) {
            $info[$role]['piao_time'] = time();
        }
        $info[$role]['next'] = $next;
        $info[$role]['status'] = $status;
        $this->memcache->set($key, $info);
        $this->storeRidByFd($fd, $rid);
    }

    public function storeStatus($rid, $status)
    {
        $key = self::PREFIX_ST . $rid;
        $info = $this->memcache->get($key);
        $info[] = $status;
        $this->memcache->set($key, $info);
    }

    public function getStatus($rid)
    {
        $key = self::PREFIX_ST . $rid;
        return  $this->memcache->get($key);
    }

    public function delStatus($rid)
    {
        $key = self::PREFIX_ST . $rid;
        return  $this->memcache->delete($key);
    }

    public function resetRoomInfo($rid, $players)
    {
        $key = self::PREFIX . $rid;
        $this->memcache->set($key, $players);
    }

    public function getRoomInfo($rid)
    {
        $key = self::PREFIX . $rid;
        $players = $this->memcache->get($key);
        return $players;
    }

    public function getRoleInfo($rid, $mid)
    {
        $where['id'] = $rid;
        $where['status'] = 1;
        $room = $this->getOne(['id' => $rid]);
        if (!$room) {
            return false;
        }
        $member = new Member();
        switch ($mid) {
            case $room['host'] :
                $arr['role'] = 'host';
                $arr['member'] = $member->getMember($room['host']);
                break;
            case $room['r1'] :
                $arr['role'] = 'r1';
                $arr['member'] = $member->getMember($room['r1']);
                break;
            case $room['r2'] :
                $arr['role'] = 'r2';
                $arr['member'] = $member->getMember($room['r2']);
                break;
        }
        return $arr;
    }

    public function getRoomData($id,$mid)
    {
        $where['id'] = $id;
//        $where['status'] = 1;
        $room = $this->getOne(['id' => $id]);
        if (!$room) {
            abort(404);
        }
        $arr['room'] = $room;
        switch ($mid) {
            case $room['host'] :
                $arr['role'] = 'host';
                $arr['order'] = ['left' => 'r2', 'right' => 'r1', 'footer' => 'host'];
                break;
            case $room['r1'] :
                $arr['role'] = 'r1';
                $arr['order'] = ['left' => 'host', 'right' => 'r2', 'footer' => 'r1'];
                break;
            case $room['r2'] :
                $arr['role'] = 'r2';
                $arr['order'] = ['left' => 'r1', 'right' => 'host', 'footer' => 'r2'];
                break;
            default :
                return ['status'=>-1];
        }
        $member = new Member();
        $arr['players']['host'] = $member->getMember($room['host']);
        if ($room['r1']) {
            $arr['players']['r1'] = $member->getMember($room['r1']);
        }
        if ($room['r2']) {
            $arr['players']['r2'] = $member->getMember($room['r2']);
        }
        return $arr;
    }

}